//
//  UITableViewCell_runtime.swift
//  AJiTai
//
//  Created by 周博 on 2020/6/11.
//  Copyright © 2020 BO ZHOU. All rights reserved.
//

import UIKit

private var UITableViewCell_isNeedPreventRepeatClicks: String = "UITableViewCell_isNeedPreventRepeatClicks"


// 阻止多重点击的时间间隔
private var UITableViewCell_repeatClicksInterval: TimeInterval = 0.5

public extension UITableViewCell {

    /**
     * 运行时初始化
     */
    override open class func initRunTime() {

        // 父类UIView运行时已经交换, 这里不需要交换
        // 交换awakeFromXib方法
//        exchange(originalSelector: #selector(awakeFromNib), swizzledSelector: #selector(exchange_awakeFromNib))

        // 交换setSelect方法, 用于处理cell短时间多次点击, 或者网络请求期间多次点击导致的多重push问题
        exchange(originalSelector: #selector(setSelected(_:animated:)), swizzledSelector: #selector(exchange_setSelected(_:animated:)))
    }


    // 是否阻止多重点击, 默认为true
    @IBInspectable var isNeedPreventRepeatClicks: Bool {
        get {
            if let isNeedPreventRepeatClicks = objc_getAssociatedObject(self, &UITableViewCell_isNeedPreventRepeatClicks) as? Bool {
                return isNeedPreventRepeatClicks
            } else {
                return true
            }
        }
        set {
            objc_setAssociatedObject(self, &UITableViewCell_isNeedPreventRepeatClicks, newValue, .OBJC_ASSOCIATION_ASSIGN)
        }
    }

    // 交换awakeFromXib方法
    @objc override func exchange_awakeFromNib() {
        super.exchange_awakeFromNib()

        self.selectionStyle = .none
    }

    // 交换setSelected方法, 用于控制短时间多次点击造成多重push的问题
    @objc func exchange_setSelected(_ selected: Bool, animated: Bool) {

        if isNeedPreventRepeatClicks {
            self.isUserInteractionEnabled = false
            DispatchQueue.main.asyncAfter(deadline: .now() + UITableViewCell_repeatClicksInterval) {
                self.isUserInteractionEnabled = true
            }
        }
        exchange_setSelected(selected, animated: animated)
    }

}
